package com.example.xuegengwang.xuegengwang.fragment;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.xuegengwang.xuegengwang.R;
import com.example.xuegengwang.xuegengwang.adapter.FourListViewAdapter;
import com.example.xuegengwang.xuegengwang.bean.FourPageListItemBean;
import com.example.xuegengwang.xuegengwang.bean.Userbean;
import com.google.gson.Gson;
import com.makeramen.roundedimageview.RoundedImageView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import common.BaseFragment;
import common.Constant;
import fourFragment.activity.MyAttention;
import fourFragment.activity.MyQuestion;
import fourFragment.activity.PersonalInfo;
import fourFragment.activity.Setting;
import https.InterNetController;
import https.handler.ErrorPageHandler;
import guidePage.LoginPage;
import in.srain.cube.views.ptr.PtrFrameLayout;
import pay.activity.EnCash;
import utils.KeyBoard;
import view.MyAddressPicker;
import view.MyImageLoader;
import utils.PickerUtils;
import utils.SPUtils;
import utils.ShowImageUtils;
import view.MyOptionPicker;
import view.MyPtrRefresh_LoadView;
import web.activity.WebPage;

import static android.app.Activity.RESULT_CANCELED;

/**
 * 我的fragment
 */
@SuppressLint("ValidFragment")
public class FourFragment extends BaseFragment implements View.OnClickListener, AdapterView.OnItemClickListener {
    private View view;
    private ListView listView;
    private FourListViewAdapter fourExpandableListViewAdapter;
    private View header;
    private ArrayList<FourPageListItemBean> itemList = new ArrayList<>();
    private String id;//用户id

    private MyPtrRefresh_LoadView four_fragment_refreshLayout;
    private RelativeLayout four_fragment_header_layout;//头部点击位置
    private RelativeLayout four_fragment_header_qiandao_btn;//签到
    private RoundedImageView four_fragment_header_ima;
    private TextView four_fragment_header_login_tv;//立即登录
    private TextView four_fragment_header_qiandao_tv;//已签到天数
    private TextView four_fragment_header_jifen_tv;//积分
    private TextView four_fragment_header_date;//距离高考n天
    private LinearLayout four_fragment_header_jifen_layout;//积分商城

    private ImageView common_back;
    private ImageView common_search;
    private TextView common_title;
    private Userbean userbean;
    private List<String> images = new ArrayList<>();//装头像用的，里面只装一个数据

    private String tel = "";
    private String exam_year = "";
    private String school_prov = "";
    private String school_city = "";
    private String school_dist = "";
    private String type = "";
    private String count = "";

    private final int GETDATA = 0;
    private final int COMPLETEINFO = 1;
    private final int QIANDAO = 2;

    private boolean firstOpen = true;

    public static final int COMPLETEINFO_CODE = 2;
    public static final int LOGOUT_CODE = 3;


    private myReceiver myReceiver;
    private MyAddressPicker addressPicker;//地区选择器

    private ErrorPageHandler myHandler = new ErrorPageHandler(true) {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case Constant.ERROR_CODE_SUCCESS:
                    if (four_fragment_refreshLayout != null) {
                        if (four_fragment_refreshLayout.isRefreshing()) {
                            four_fragment_refreshLayout.OnRefreshComplete();
                        }
                    }
                    switch (msg.arg1) {
                        case GETDATA:
                            firstOpen = false;
                            Gson gson = new Gson();
                            userbean = gson.fromJson((String) msg.obj, Userbean.class);
                            if (userbean != null) {
                                Userbean.UserBean userBean = userbean.getUser();
                                if (userBean != null) {
                                    exam_year = userBean.getExam_year();
                                    if (!TextUtils.isEmpty(userBean.getName())) {
                                        four_fragment_header_login_tv.setText(userBean.getName());
                                    } else {
                                        four_fragment_header_login_tv.setText("未命名用户");
                                    }
                                    four_fragment_header_qiandao_tv.setText("已连续签到" + userBean.getAlready_day() + "天");
                                    four_fragment_header_jifen_tv.setText(userBean.getScore() + "分");
                                    four_fragment_header_date.setText(userBean.getExam_day());
                                    String area = "";
                                    if (!TextUtils.isEmpty(userBean.getSchool_prov())) {
                                        area += userBean.getSchool_prov();
                                    }
                                    if (!TextUtils.isEmpty(userBean.getSchool_city())) {
                                        area += "-" + userBean.getSchool_city();
                                    }
                                    if (!TextUtils.isEmpty(userBean.getSchool_dist())) {
                                        area += "-" + userBean.getSchool_dist();
                                    }
                                    itemList.get(1).setMore(userBean.getType());
                                    itemList.get(2).setMore(area);
                                    count = userBean.getCount();
                                    itemList.get(3).setMore(count);
                                    itemList.get(5).setMore(userBean.getMoney());
                                    if (!TextUtils.isEmpty(userBean.getCount())) {
                                        itemList.get(7).setCount(Integer.parseInt(userBean.getUnwatchcount()));
                                    } else {
                                        itemList.get(7).setCount(0);
                                    }
                                    MyImageLoader.showImage(userBean.getHeadimgurl(), four_fragment_header_ima);
                                    fourExpandableListViewAdapter.notifyDataSetChanged();
                                }
                            } else {
                                resetView();
                            }
                            break;
                        case COMPLETEINFO:
                            //完善个人信息
                        case QIANDAO:
                            getDataFromInterNet(false);//刷新界面
                            break;
                        default:
                            break;
                    }
                    break;
                case Constant.ERROR_CODE_FAILD:
                    if (four_fragment_refreshLayout != null) {
                        four_fragment_refreshLayout.OnRefreshComplete();
                    }
                    break;
                default:
                    break;
            }
        }
    };

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_four, container, false);
        initView();
        initData();
        initListView();
        isLogin();
        registerReceiver();
        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        if (getMyActivity() != null) {
            if (firstOpen) {
                getDataFromInterNet(true);
            } else {
                getDataFromInterNet(false);
            }
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            if (getMyActivity() != null) {
                if (firstOpen) {
                    getDataFromInterNet(true);
                } else {
                    getDataFromInterNet(false);
                }
            }
        }
    }

    private void initView() {
        four_fragment_refreshLayout = (MyPtrRefresh_LoadView) view.findViewById(R.id.four_fragment_refreshLayout);
        four_fragment_refreshLayout.ChangeMode(true, false);
        four_fragment_refreshLayout.setMyPtrHandler(new MyPtrRefresh_LoadView.MyPtrHandler() {
            @Override
            public void onLoadMoreBegin(PtrFrameLayout frame) {

            }

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                if (getMyActivity() != null) {
                    getDataFromInterNet(false);
                }
            }
        });
        common_back = (ImageView) view.findViewById(R.id.common_back);
        common_back.setVisibility(View.INVISIBLE);
        common_search = (ImageView) view.findViewById(R.id.common_search);
        common_search.setVisibility(View.INVISIBLE);
        common_title = (TextView) view.findViewById(R.id.common_title);
        common_title.setText("我的");
    }

    private void initListView() {
        header = LayoutInflater.from(getMyActivity()).inflate(R.layout.four_fragment_header, null);
        four_fragment_header_layout = (RelativeLayout) header.findViewById(R.id.four_fragment_header_layout);
        four_fragment_header_qiandao_btn = (RelativeLayout) header.findViewById(R.id.four_fragment_header_qiandao_btn);
        four_fragment_header_login_tv = (TextView) header.findViewById(R.id.four_fragment_header_login_tv);
        four_fragment_header_qiandao_tv = (TextView) header.findViewById(R.id.four_fragment_header_qiandao_tv);
        four_fragment_header_jifen_tv = (TextView) header.findViewById(R.id.four_fragment_header_jifen_tv);
        four_fragment_header_date = (TextView) header.findViewById(R.id.four_fragment_header_date);
        four_fragment_header_ima = (RoundedImageView) header.findViewById(R.id.four_fragment_header_ima);
        four_fragment_header_jifen_layout = (LinearLayout) header.findViewById(R.id.four_fragment_header_jifen_layout);
        four_fragment_header_layout.setOnClickListener(this);
        four_fragment_header_ima.setOnClickListener(this);
        four_fragment_header_qiandao_btn.setOnClickListener(this);
        four_fragment_header_jifen_layout.setOnClickListener(this);

        fourExpandableListViewAdapter = new FourListViewAdapter(getMyActivity(), itemList);
        listView = (ListView) view.findViewById(R.id.four_fragment_lv);
        listView.addHeaderView(header);
        listView.setAdapter(fourExpandableListViewAdapter);
        listView.setOnItemClickListener(this);
    }

    public void resetView() {
        four_fragment_header_login_tv.setText("立即登录");
        four_fragment_header_qiandao_tv.setText("已连续签到 n 天");
        four_fragment_header_jifen_tv.setText("n 分");
        four_fragment_header_date.setText("距离高考 n 天");
        four_fragment_header_ima.setImageResource(R.mipmap.default_ima_circle);
        itemList.get(1).setMore("");
        itemList.get(2).setMore("");
        itemList.get(3).setMore("");
        itemList.get(5).setMore("");
        itemList.get(6).setMore("");
        itemList.get(5).setMore("");
        itemList.get(8).setMore("");
        itemList.get(8).setCount(0);
        fourExpandableListViewAdapter.notifyDataSetChanged();
    }

    private boolean isLogin() {
        SharedPreferences sharePrence = SPUtils.getSharedPreferences();
        id = sharePrence.getString(Constant.USER_ID, "");
        if (TextUtils.isEmpty(id)) {
            //用户为空
            return false;
        } else {
            return true;
        }
    }

    private void initData() {
        String name1 = getMyActivity().getResources().getString(R.string.four_fragment_item_name1);
        String name2 = getMyActivity().getResources().getString(R.string.four_fragment_item_name2);
        String name3 = getMyActivity().getResources().getString(R.string.four_fragment_item_name3);
        String name4 = getMyActivity().getResources().getString(R.string.four_fragment_item_name4);
//        String name5 = getMyActivity().getResources().getString(R.string.four_fragment_item_name5);
        String name6 = getMyActivity().getResources().getString(R.string.four_fragment_item_name6);
        String name7 = getMyActivity().getResources().getString(R.string.four_fragment_item_name7);
        String name8 = getMyActivity().getResources().getString(R.string.four_fragment_item_name8);
        Drawable drawable7 = getMyActivity().getResources().getDrawable(R.mipmap.favourite_ima);
        Drawable drawable2 = getMyActivity().getResources().getDrawable(R.mipmap.location_ima);
        Drawable drawable8 = getMyActivity().getResources().getDrawable(R.mipmap.setting_ima);
        Drawable drawable1 = getMyActivity().getResources().getDrawable(R.mipmap.subject_ima);
        Drawable drawable3 = getMyActivity().getResources().getDrawable(R.mipmap.float_ima);
        Drawable drawable4 = getMyActivity().getResources().getDrawable(R.mipmap.money_ima);
//        Drawable drawable5 = getMyActivity().getResources().getDrawable(R.mipmap.vip_ima);
        Drawable drawable6 = getMyActivity().getResources().getDrawable(R.mipmap.ask_ima);
        FourPageListItemBean fourPageListItemBean1 = new FourPageListItemBean(name1, drawable1, true, null);
        FourPageListItemBean fourPageListItemBean2 = new FourPageListItemBean(name2, drawable2, true, null);
        FourPageListItemBean fourPageListItemBean3 = new FourPageListItemBean(name3, drawable3, true, null);
        FourPageListItemBean fourPageListItemBean4 = new FourPageListItemBean(name4, drawable4, true, null);
//        FourPageListItemBean fourPageListItemBean5 = new FourPageListItemBean(name5, drawable5, true, null);
        FourPageListItemBean fourPageListItemBean6 = new FourPageListItemBean(name6, drawable6, true, null);
        FourPageListItemBean fourPageListItemBean7 = new FourPageListItemBean(name7, drawable7, true, null);
        FourPageListItemBean fourPageListItemBean8 = new FourPageListItemBean(name8, drawable8, true, null);
        FourPageListItemBean backGroundItem = new FourPageListItemBean(name1, drawable1, false, null);
        itemList.add(backGroundItem);
        itemList.add(fourPageListItemBean1);
        itemList.add(fourPageListItemBean2);
        itemList.add(fourPageListItemBean3);
        itemList.add(backGroundItem);
        itemList.add(fourPageListItemBean4);
//        itemList.add(fourPageListItemBean5);
        itemList.add(backGroundItem);
        itemList.add(fourPageListItemBean6);
        itemList.add(fourPageListItemBean7);
        itemList.add(fourPageListItemBean8);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Intent i = new Intent();
        if (!isLogin()) {
            i.setClass(getMyActivity(), LoginPage.class);
            startActivityForResult(i, Constant.LOGIN_REQUEST_CODE);
            getMyActivity().overridePendingTransition(R.anim.zoomin, 0);
            return;
        } else {
            switch (position) {
                case 2:
                    //科目
                    MyOptionPicker optionPicker = PickerUtils.showSubjectSelector(getMyActivity());
                    optionPicker.setOnOptionPickListener(new MyOptionPicker.OnOptionPickListener() {
                        @Override
                        public void onOptionPicked(String option) {
                            type = option;
                            completeInfo();
                        }
                    });
                    break;
                case 3:
                    //地区
                    addressPicker = PickerUtils.showAddressSelector(getMyActivity());
                    if (addressPicker != null) {
                        addressPicker.setOnAddressPickListener(new MyAddressPicker.OnAddressPickListener() {
                            @Override
                            public void onAddressPicked(String province, String city, String county) {
                                school_prov = province;
                                school_city = city;
                                school_dist = county;
                                completeInfo();
                            }
                        });
                    }
                    break;
                case 4:
                    //分数
                    showScoreDialog();
                    break;
                case 6:
                    //我的余额
                    i.setClass(getMyActivity(), EnCash.class);
                    i.putExtra("money", userbean.getUser().getMoney());
                    startActivity(i);
                    break;
//                case 7:
//                    //开通会员
//                    break;
                case 8:
                    //我的提问
                    i.setClass(getMyActivity(), MyQuestion.class);
                    startActivity(i);
                    break;
                case 9:
                    //关注
                    i.setClass(getMyActivity(), MyAttention.class);
                    startActivity(i);
                    break;
                case 10:
                    //设置
                    i.setClass(getMyActivity(), Setting.class);
                    startActivityForResult(i, LOGOUT_CODE);
                    break;
                default:
                    break;
            }
        }
    }

    private void showScoreDialog() {
        KeyBoard.showKeyBoard();
        final Dialog dialog = new Dialog(getMyActivity(), R.style.centerDialog);
        dialog.setContentView(R.layout.fourfragment_score_layout);
        ImageView fourfragment_score_layout_cancel = (ImageView) dialog.getWindow().findViewById(R.id.fourfragment_score_layout_cancel);
        fourfragment_score_layout_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //取消按钮
                dialog.dismiss();
            }
        });
        final EditText fourfragment_score_layout_edt = (EditText) dialog.getWindow().findViewById(R.id.fourfragment_score_layout_edt);
        //配置editView
        fourfragment_score_layout_edt.setText(count);
        fourfragment_score_layout_edt.setSelection(fourfragment_score_layout_edt.getText().length());

        ImageView fourfragment_score_layout_confirm = (ImageView) dialog.getWindow().findViewById(R.id.fourfragment_score_layout_confirm);
        fourfragment_score_layout_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //完成填写分数
                count = fourfragment_score_layout_edt.getText().toString();
                if (TextUtils.isEmpty(count)) {
                    count = "0";
                }
                completeInfo();
                dialog.dismiss();
            }
        });
        dialog.show();
    }

    @Override
    public void onClick(View v) {
        if(v.getId()== R.id.four_fragment_header_jifen_layout){
            //积分商城
            Intent i = new Intent(getMyActivity(), WebPage.class);
            i.putExtra("url", "http://xuegengwang.com/jinzhao/page/shopping_mall.html?ac_id="+id+"&os=Android");
            startActivity(i);
            return;
        }
        if (!isLogin()) {
            Intent i = new Intent();
            i.setClass(getMyActivity(), LoginPage.class);
            startActivityForResult(i, Constant.LOGIN_REQUEST_CODE);
            getMyActivity().overridePendingTransition(R.anim.zoomin, 0);
            return;
        } else {
            switch (v.getId()) {
                case R.id.four_fragment_header_ima:
                    images.clear();//一次只加一个头像
                    if (userbean != null) {
                        images.add(userbean.getUser().getHeadimgurl());
                        ShowImageUtils showImageUtils = new ShowImageUtils();
                        showImageUtils.showImageUtils(getMyActivity(), four_fragment_header_ima, images, 0);
                    }
                    break;
                case R.id.four_fragment_header_layout:
                    if (!isLogin()) {
                        Intent i = new Intent();
                        i.setClass(getMyActivity(), LoginPage.class);
                        getMyActivity().startActivityForResult(i, Constant.LOGIN_REQUEST_CODE);
                        getMyActivity().overridePendingTransition(R.anim.zoomin, 0);
                    } else {
                        Intent i = new Intent(getMyActivity(), PersonalInfo.class);
                        four_fragment_header_ima.setDrawingCacheEnabled(true);
                        Bitmap bm = four_fragment_header_ima.getDrawingCache();
                        i.putExtra("headIma", bm);
                        i.putExtra("name", four_fragment_header_login_tv.getText().toString());
                        i.putExtra("year", exam_year);
                        startActivityForResult(i, COMPLETEINFO_CODE);
                    }
                    break;
                case R.id.four_fragment_header_qiandao_btn:
                    qianDao();
                    break;
                default:
                    break;
            }
        }
    }

    public void getDataFromInterNet(boolean waitDialog) {
        new InterNetController(getMyActivity(), Constant.PERSONALINFO, myHandler, null, GETDATA, waitDialog);
    }


    public void qianDao() {
        new InterNetController(getMyActivity(), Constant.SIGNIN, myHandler, null, QIANDAO, false);
    }

    private void completeInfo() {
        HashMap<String, String> hashMap = new HashMap<>();
        if (!TextUtils.isEmpty(tel)) {
            hashMap.put("tel", tel);
        }
        if (!TextUtils.isEmpty(exam_year)) {
            hashMap.put("exam_year", exam_year);
        }

        if (!TextUtils.isEmpty(school_prov)) {
            hashMap.put("school_prov", school_prov);
        }

        if (!TextUtils.isEmpty(school_city)) {
            hashMap.put("school_city", school_city);
        }

        if (!TextUtils.isEmpty(school_dist)) {
            hashMap.put("school_dist", school_dist);
        }
        if (!TextUtils.isEmpty(type)) {
            hashMap.put("type", type);
        }
        if (!TextUtils.isEmpty(count)) {
            hashMap.put("count", count);
        }
        new InterNetController(getMyActivity(), Constant.COMPLETEINFO, myHandler, hashMap, COMPLETEINFO, false);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_CANCELED) {
            switch (requestCode) {
                case Constant.LOGIN_REQUEST_CODE:
                    //登录完了
                case FourFragment.COMPLETEINFO_CODE:
                    //用户信息填完了
                    getDataFromInterNet(false);//刷新界面
                    break;
                case FourFragment.LOGOUT_CODE://登出
                    resetView();
                    break;
                default:
                    break;
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        getMyActivity().unregisterReceiver(myReceiver);
    }

    private void registerReceiver() {
        //注册广播
        myReceiver = new myReceiver();
        IntentFilter intentFilter = new IntentFilter(Constant.ACTION_UPDATE_PERSONAL_INFO);
        getMyActivity().registerReceiver(myReceiver, intentFilter);
    }

    class myReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (getMyActivity() != null) {
                getDataFromInterNet(false);
            }
        }
    }
}
